package com.sunwhite.herostore.handler;


import com.google.protobuf.GeneratedMessageV3;
import com.sunwhite.herostore.cmdhandler.*;
import com.sunwhite.herostore.common.BroadCaster;
import com.sunwhite.herostore.common.MainThreadProcessor;
import com.sunwhite.herostore.common.UserManager;
import com.sunwhite.herostore.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GameMsgHandler extends SimpleChannelInboundHandler<Object> {
    public static final Logger log = LoggerFactory.getLogger(GameMsgHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        BroadCaster.addChannel(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);

        BroadCaster.remove(ctx.channel());

        // 先拿到用户 Id
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();

        if (null == userId) {
            return;
        }
        log.info("用户离线,userId={}",userId);
        //移除用户
        UserManager.remove(userId);

        //广播用户立场消息
        BroadCaster.broadQuit(userId);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (msg instanceof GeneratedMessageV3) {
            // 通过主线程处理器处理消息
            MainThreadProcessor.getInstance().process(ctx, (GeneratedMessageV3) msg);

        }

    }


    /**
     * 转型消息对象
     * @param msg
     * @param <T>
     * @return
     */
    private <T extends GeneratedMessageV3> T cast(Object msg) {
        if (null==msg||!(msg instanceof GeneratedMessageV3)){
            return null;
        }
        return (T) msg;
    }

}
